

# REPLICATION SCRIPT FOR "Citizens' economic recovery models for a pandemic"
# ASMUS LETH OLSEN AND ANDERS WOLLER
# APRIL 7 2022
# 
# SCRIPT WAS RUN ON with
# x86_64-apple-darwin17.0     
# R version 4.0.5 (2021-03-31)
# (obs might encounter replication issues on PC)

rm(list = ls(all = TRUE))
setwd(dirname(rstudioapi::getSourceEditorContext()$path)) # 

# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# PACKAGES
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

packages <- c('quanteda', 'quanteda.textmodels', 'corpus', 'RTextTools', 'gridExtra', 'corrplot', 'tidytext', 'ngram', 'reshape2', 'tidyr', 'readstata13', 'haven', 'tidyverse', 'ggforce', 'ggrepel', 'doParallel', 'sqldf', 'stats', 'sf', 'raster', 'rgdal', 'sp', 'rdd', 'rdrobust', 'lfe', 'stargazer', 'parallel', 'fastLink', 'RecordLinkage', 'ggplot2', "rgdal", "data.table", "dplyr", "stringr", "stringdist", 'rgeos', 'sp', 'rgdal', 'raster', 'readxl', 'readstata13', 'maptools')
lapply(packages, require, character.only=T)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# DATA
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# SURVEY
# obs: dataverse might change file format to ".tab".
survey <- fread("survey_limited.csv")



# CONTEXT
business_trust <- fread("businesstrust.csv")
consume <- fread("consumertrust.csv")

# GDP: Realvækst i forhold til foregående periode (pct.), sæsonkorrigeret
GDP <- fread("GDP.csv")
GDP <- GDP[,3:4]
# employed: Realvækst i forhold til foregående periode (pct.). Samlet antal beskæftigede (1000 personer). Sæsonkorrigeret
employed <- fread("unemployment.csv")
employed <- employed[,2:3]


# STOPWORDS
stopwords <- read.table('https://gist.githubusercontent.com/berteltorp/0cf8a0c7afea7f25ed754f24cfc2467b/raw/305d8e3930cc419e909d49d4b489c9773f75b2d6/stopord.txt', encoding = 'UTF-8')# fwrite(stopwords, 'stopwords.csv')
stopwords <- stopwords$V1[!(stopwords$V1 %in% c('op', 'ned', 'uden', 'ikke'))]
stopword <- paste('( |[[:punct:]]|^)(', paste(stopwords, collapse = '|'), ') ', sep='')


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# PROCESSING DATA
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
prep_text_reply <- function(x, var, name='solution'){
  setDT(x)[, c(name) := tolower(gsub('(\\n|[[:punct:]])', ' ', x[[var]]))]
  x[, c(name) := tolower(gsub(' dk&?', ' danmark', x[[name]]))]
  x[, c(name) := gsub(stopword, ' ', x[[name]])][, c(name) := gsub('  ', ' ', x[[name]])]
  x <<- x }
prep_text_reply(survey, 'Q27', 'solution')
prep_text_reply(survey, 'Q20_text', 'solution_w1')


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# DICTIONARY METHOD: demand-side economics VS classical economics
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

categories <- function(x){
  demand <<- paste(c("yde(|r) (lån|tilskud)", "(økonomisk|politisk) (stimul|håndsrækning)", "borger( )?løn", 'øge(|t) (offentlig(|e|t)) (forbrug|investering|støtte)', "offentlig støtte", "økonomisk understøttelse", "støtte (lønkompensation|offentlig hjælp|samfundet økonomisk)",
                     "økonomisk(|e) (støtte|hjælp|bistand|pakker|hjælpepakker|støtteforanstaltninger|offentlig hjælp|støttepakker|støtteordninger|tilskud|tiltag|indsprøjtning)", "(økonomien|erhvervslivet|erhvervsdrivende|brancher|virksomheder|sektor|industri(|en)|firmaer) (stimulere|hjælpe)", 
                     "efterspørgsel", "renover (offentlige|kommunale)", "hæv løn", "støtteordninger", "støttepakker", "hjælp(e)?pakke", "støtte ordninger", "øge(t)? jobskabelse", "hjælpepakker", "hjælpe pakker", "offentlige investeringer", "(bruge(|r)|give)([a-zæåø ]{1,10})?penge", "holde hånden", "give folk penge",
                     "ferie( )?penge", "kapital indsprøjt", "(fremskynde|fremrykke|rykke|brug) offentlige", "nødpakke", "folk bruge", "brug penge", "pump(|e|er) (penge|offentlige midler)", "føre ekspansiv",
                     "støt(|ter|te)([a-zæåø ]{1,10})?økonomiske", "(højne|øge)([a-zæåø ]{1,20})?købekraften", "stimulere", "sætte (kommunale|offentlige|statslige|offentlige)", "øg(|e|et)? forbrug", "kompencere([a-zæåø ]{1,10})?indkomst",
                     "økonomisk hjælp", 'offentlig(e)? (klimaprojekter|byggeri)', "styrke offentlige sektor", "prioritere velfærdsstaten","istandsættelser offentlige", "hold(e|er)? forbrug", "gang ([a-zæåø ]{1,10})?(forbrug|handlen|handle|købe|spender)", "(forbruget|handlen) (i)?gang", "grøn(|ne) omstilling", "beskæftigelsen", "optage(.*) statsgæld", "købelyst", "nye projekter", "støtte økonomisk",
                     "håndsrækninger([a-zæåø ]{1,10})?brancher", "bruge milliard", "regeringen([a-zæåø ]{1,10})?hjælpe", "investere (infrastruktur|økonomisk)", "investering", "sikre (job|arbejdspladser)", "sikre beskæftigelse", "motorveje", "arbejdsløshed(en)? ned", "undgå([a-zæåø ]{1,10})?arbejdsløs", "(undlade|undgå) fyringer", "holder forbruget oppe", "holder hånd(|en) (økonomi|virksomhed)", "(sikre|skabe) arbejdspladser", "subsidi",
                     "(offentlig(e|)|statslig(|e)|regeringen) (projekter|anlægs|opgave(|r)|støtte(|r)|håndsrækning|(til|ud)deler (midler|kontante)|understøtter|åbner)", "statsstøtte", "staten (under)?støtte(|r)", "støtte private", "(hjælpe|støtte|sikre) små", "offensiv vækstpolitik", 
                     "(hjælpe(|r)|stimulere(|r)|booste(|r)|(under)?støtte(|r)|sikre(|r))([a-zæåø ]{1,10})?(sektorer|restauranter|servicebranchen|forretninger|brancher|butikker|firmaer|erhvervslivet|erhvervsdrivende|økonomien|erhverv|privat|virksomheder|industri(|en))", "(private|offentlig(|e|t)|indenlandske) forbrug",  
                     'monetær politik', 'pengepolitik', "lånemarked", "holde renterne nede", "(lavrente|rentefri(e)?) udlån", "keynesiansk", "hjælp([a-zæåø ]{1,10})?selvstændige", "stifte gæld", "infrastrukturprojekter", 'banker(|s) (udlåns|)rente', 'rente (bank|)lån', "statslån", "fastholdelse rente", "større lånefrihed", 
                     "(ekspansiv|lempelig)", "finanspolitik", "rimelig(e|) renter", "låner([a-zæåø ]{1,10})?penge", 
                     'penge i samfundet', 'håndværker(.)?fradrag', '(fart|gang) i (forretning|industri|virksomheder|erhverv|produktion)', 'helikopter(.)?penge', '(handle|forbruge|købe)([a-zæåø ]{1,5})?som før',
                     'holde oven vande', "kapital indsprøjt", 'en pose penge', '(anlægs|bygge)(projekter|opgaver)', 'penge nok i statskassen', 'penge i samfundet', '(sikre|støtte|hjælpe)(.)? (landbrug|eksport|erhverv|økonomi)'), collapse='|')
  health <<- paste(c("test test", "tilskynde adfærd", "hold(|e|er) afstand", "sund fornuft", "bliv hjemme", "arbejd(|e) hjemmefra", "epedemi", "smittekurve", "nærkontakt", "sundhedsmæssigt forsvarlig", 
                     "(håndhæve|overholde|bibeholde)([a-zæåø ]{1,10})?(restriktion|retningslinjer|anbefalinger|anvisninger|forsigtighedsreglerne|påbud|forholdsregler|tiltag|regler)",
                     "tiltag regeringen", "behandling", "fysisk kontakt", "brems(|e|et) smitte", "helbredsmæssige", "sundhedsmyndighed", "medicinsk forskn", "styrke hospitalerne", "forhaste(t)? genåbn", "gruppeimmunitet", "streng kontrol","smittebære", "sundhed", "folk adskilt", "holde lukket (en|to|tre|fire|fem|seks|1|2|3|4|5|6)", "finde([a-zæåø ]{1,10})?medicin", "(skærpe|forlænge) karantæne", "forbliver (overholdt|respekteret)", "regeringens anvisninger", "vask(e|) hænder", 'selvisolation', 'øge antal(|let) tests', '(vaccine|vaksine|vacine|vaccination)', "værnemidler", "fortsætte test",  "sundhedsmæssige risici",
                     "socialt samvær", "hygiejne", "prioritere sundhed", "immunitet", "(social|fysisk) distanceri", "holde (danmark|landet|samfundet) lukket", "([a-zæåø ]{1,15})?test", "fortsætte (nedlukningen|hjemmearbejde|nuværende)", "indæmn", "bliv hjemme", "mundbind", "lukket landet", "lukket hurtigt muligt", "sundhedskrise", "forskudt arbejdstid", "sygdomskontrollen", "isol([a-zæåø ]{1,20})? (smit|syg|ældre|svag|udsat|risiko|riciko|sårbar|gamle)", "teste målrettet", "mindske smitterisikoen", 
                     "stoppe smitte(|spredningen)", '(begræns|undgå) smitte', 'sikre (epidemien|pandemien)', "folkets sundhed", 'smittekæde', 'distancering', 'udgangsforbud', 'sikre helbred', 
                     'gribe tidligt ind', 'redde så mange', "smittefaren", "mørketal", "desinfektion", "immune", "spredning", "sundhedsvæsenets kapacitet", "flokimmun"), collapse='|')
  authority <<- paste(c("regeringens|myndighedernes|folketingets|statsministerens|fagkundskabens|beslutningstager|embedsværk|forsker|forskning) (anvisninger|råd)", "(følge(|r)|overholde(|r)) (|retningslinjer|forholdsregler|påbud|regeringens|myndighedernes|folketingets|statsministerens|fagkundskabens|beslutningstager|embedsværk|forsker|forskning)", 
                        '(efterlev|følg)([a-zæåø ]{1,5})?(anvisninger|guidelines|forholdsregler|påbud|anbefalinger|myndighed)', "dygtig([a-zæåø ]{1,10})?(politikere||beslutningstager)", '(dygtig|handlekraftig|stærk|kompetent|troværdig)([a-zæåø ]{1,15})? regering',
                        "stol([a-zæåø ]{1,15})?(regeringen|folketinget|økonomisk rådgiver||embedsværk|beslutningstager|myndighed|sundhed|forsker|forskning)", "mette", "[overholder] regler", "holde fast i (tiltag|restriktioner)", "god regering", "tillid([a-zæåø ]{1,15})?(regering|myndighed|politiker|beslutningstager|ekspert|expert|embedsværk|forsker|forskning)", "fortsætte([a-zæåø ]{1,10})?lin(i|j)e", 
                        "folk lytter", "(regeringen|myndighederne) (siger|råder)", "(regeringen|folketinget|eksperter(ne)?||beslutningstager|embedsværk|forsker|forskning) (siger|gør|finder)", "(lyt|følg|ret)([a-zæåø ]{1,20})?(myndighederne|eksperter|fagkundskabens|folk indsigt|regeringen|mette|sundheds|søren brostrøm|statsminister|beslutningstager|embedsværk|forsker|forskning|restriktion)", "dygtige fagfolk", "fortsæt([a-zæåø ]{1,10})? strategi", '(regering|myndighed|ekspert|institut|styrelse|nuværende|embedsværk)([a-zæåø ]{1,10})? anbefaling',
                        'strategi([a-zæåø ]{1,30})?regering'), collapse='|')
  international_econ <<- paste(c('(hjælp|støtte)([a-zæåø ]{1,10})?lande', 'stærk eksport', 'verdensøkonomien', "åbne grænser", "krisen global","internationale relation", "gang eksporten", "arbejdskraft udlandet komme", "handel", "handelpartnere", "samhandel", "internationalt samarbejde", "samarbejde lande", 
                                 "resten verden", "eu samarbejd", "globalt plan", "globalisering", "lille økonomi", "hjælpe europæiske", "who", "gang turismen", "åben økonomi", 'omverdenen', 'hele verden', 'verdensplan', "afhængige (export|verdensmarked)", "afhængig globale", "(samarbejde|afhængig)([a-zæåø ]{1,10})?(omverdenen|lande)", "globale økonomi", 
                                 "(afhængig(e)?|samarbejde) eu", "global(e)? verden", "hjælpe udlandet", "verdenssamfund", "verdensmarked", "exportmarkeder", '(global|international)([a-zæåø ]{1,20})? (krise|udfordring|økonomi|problem|handel|program|verden|samarbejd|fælles)', 'hele verden',
                                 'nordisk fællesskab', 'eksport', 'internationale aftaler'), collapse='|')
  climate <<- paste(c('bæredygtig', "grøn(|ne) (omstilling|projekt)", 'vedvarende sektor', "klimavenlige", "klimainvesteringer", "klimaforbedringer", "grøn teknologi", "klimabelastning", "klimaforebyggende", "hensyn klimaet", 'gavne miljøet',
                      "greentech", "grønne tiltag", 'naturressourcer', "klimakrise", "klimaområdet", "fritage grønne", "naturens ressourcer", "klimabevidst", "evig vækst", "(forbrugs|penge)ræs", "klimaudfordring", "(tænke|nye) bæredygtig", "alternative løsninger", 
                      "klimaforbedringer", "ressourceforbrug", "klimafremmende", 
                      '(klimaaftale|grøn(|ne)|bæredygtig)([a-z ]{1,20})?(energi|omstilling|klimaforandring)'), collapse='|')
  solidarity <<- paste(c("(hjælp(|e|er)|passe(|er)|stole(|r)|støtte(r)?) hinanden", "sammenhold", ('vis(.)? hensyn'), "fælles hjælp", "stå sammen", 'fællesskab', "stå sammen", "løfte flok", 
                         "stoppe nedgøre hinanden", "udvise solidaritet", '(hjælp|støt|hensyn|respekt|passe|stol)([a-zæåø ]{1,15})?hinanden', 'stå sammen', 'solidaritet', 'solidarisk'), collapse='|')
  individual <<- paste(c("sund(|e) fornuft", "samfundssind", "bliv hjemme", "egoist", "rettidig omhu", "egoister", "tage(r)? ansvar", "handle fornuftigt", 
                         '(handle|opføre)([a-z ]{1,10})?ordentlig', "fokusere([a-zæåø ]{1,10})? (positiv|negativ)"), collapse='|')
  social <<- paste(c(individual, solidarity), collapse='|')
  
  DK <<- paste(c('forstand på', 'ikke bud', 'ikke svare', "kompetent svare", "ikke kompetent", "vides ikke", "ønsker svarer", "^vides sikkerhed", "virker umuligt", "forstand økonomi", "(desværre|faktisk|simpelthen) ikke$", "forudsætninger svare", "stort spørgsmål", 'ved ikke', 'kvalificeret svare', 
                 "svært svare", "ikke forstand", "ingen mening om", "umuligt svare på", "aner virkelig ikke", "svært spørgsmål", "ingen (anelse|ide|idé|kommentar)", 'øh', 'ingen forudsætning', '(ikke|ingen) forstand', 'aner det ikke', 
                 'min stærke side', 'vidste jeg det', 'hvis jeg vidste', 'ved([a-zæåø ]{1,10})?ikke', 'ikke jeg er', 'ikke nogle ide', 'jeg er ikke', 'har ingen', 
                 'svar skyldig', '(ikke|hverken)([a-zæåø ]{1,15})?(økonom|ekspert|expert|spå|politiker|læge|finans|myndighed|kvalificeret|professor)', 
                 'svært([a-zæåø ]{1,10})?(sige|svare|vide)', "jeg ikke([a-zæåø ]{1,10})?viden", "ingen mening", "ingen bud", 'intet indblik', 'ikke indblik', '(ved|har|kan|aner|det|er) simpelthen ikke',
                 'mening om', 'ikke([a-zæåø ]{1,20})? svare', 'økonomi([a-zæåø ]{1,5})?forstand', 'forstand([a-zæåø ]{1,15})? økonomi', '(ikke|intet|ikke noget) (godt|kvalificeret|konkret|gode) bud', 'ikke([a-zæåø ]{1,10})? tænkt', 'ikke([a-zæåø ]{1,10})? gennemskue',
                 '(ekspert|økonom|regering)([a-zæåø ]{1,15})? vurdere', '(ikke|intet|ikke noget|kan ikke) svar', 'umuligt spørgsmål'), collapse='|')
  
  classical <<- paste(c('markedskræft([a-zæåø ]{1,5})?regere', 'tilbage arbejde', '(fjern|lemp)([a-zæåø ]{1,5})?restriktioner', '(slank|mindre|reducer)([a-zæåø ]{1,5})?offentlig sektor', 'svage dø', 'stærke overlever', 'undgå nedlukning', 'svensk strategi', 'isoler([a-zæåø ]{1,15})?(svage|ældre|udsatte)',
                        'indslus([a-zæåø ]{1,5})?raske', 'åbne skole', '(åbn|start|åben)([a-zæåø ]{1,10})?(forretning|industri|virksomheder|erhverv|produktion|virksomhed|økonomien|industri)', 'skub i den private sektor',
                        "hurtigst muligt", "(hurtig(s)?t|snarest) mulig", "(|gen)åbne(|t) samfundet", "(genåbning|genåbn|åbne|åbn|åben|åbner|åbning|gang|start(|e|et|er)|opluk(ning|)|opstart(|e|er|et)) (arbejdsmarked|firmaer|land|danmark|arbejdspladser|samfund|industrien|langsom|forsigtig|stille|gradvis|tidlig(t|)|tideligt|erhvervslivet|hurtigt)", "gradvis åbning",
                        "samfundet hurtigt", "folk (arbejde|igang|gang)", "nødt åbne", "genåbning samfundet", "overdreven nedlukning", "langsom genåbning", "langsom åbning", "kontrolleret åbning", "snart muligt", 
                        "(firmaer|land|danmark|arbejdspladser|virksomhed|samfund|industrien)([a-zæåø ]{1,20})?(genåb(n|en|ning|ne|ner|ent)|åbn(|e|en|er|ing)|gang|starte(|r))", "starte([a-zæåø ]{1,10})?(op|igen)",
                        "(hjulene|økonomien) ((i)?gang|hurtig)", "(reducer(|e|er)|mindske|svække) inflation", "^(åbn(|et|es|e|er)|åben)[^[:alpha:]]", "stram (ø|økonomisk) politik", "(undlad(e)?|undgå) offentlig (velfærd|udgifter) stige","udskyde klimatiltagene", "i gang", "holde investeringer tilbage", "holde(([a-zæåø ]{1,15}))(gang|kørende)", "inv(e|i)stere", "butikker(ne)? åbne", "sænke offentlig(e)? udgifter", "åbne([a-zæåø ]{1,15})private", "balance økonomien", "økonomisk balance", "holde produktionen", "kontanthjælpen skæres", "skæres  benet", "gang (hjulene|økonomien|servicesektoren)", "langsom(|t) (åbne|åbn|åben|åbner|åbning|opstart)", "begynde(|r) åbne", "arbejdspladserne gang", "sætte gang", "igang igen", "åbne op", "undgå lukke([a-zæåø ]{1,10})?(firmaer|land|danmark|arbejdspladser|samfund|industrien)",
                        "begynder åbne", "strukturreformer", "reducer([a-zæåø ]{1,10})?offentlig", "genoptages hurtigere", "normale tilstande",  "tilbagevenden", "markedet([a-zæåø ]{1,10})selv", "folk([a-zæåø ]{1,10})?arbejde", "sikre fortsatte drift", "lukning kort mulig", "hurtig opstart", "tilbage normal", "åben landet", "åben erhverslivet", "hurtigt (gang|sporet|arbejde)", "samfundet igang", "hurtigt igang", "igang hurtigt", "starte samfundet",
                        "gang danmark", "gå arbejde", "undgå nedlukning", "samfundet normali", "lukke (samfundet|stille)([a-zæåø ]{1,10})?", "næring tæring", "tæring næring", "sæt gang", "sætte samfundet([a-zæåø ]{1,10})?gang", "gradvis oplukning", "snart forsvarligt", "oplukningen", "(ophæve|lette) resriktionerne", "reducere (.*) løn", "stoppe lock( )?down",
                        "(brug|sæt(|te)|sænk(e|)|halver(|e|er)|lette|stryg)([a-zæåø ]{1,10})?(momsen|skat|afgift|skattetryk", "skatte( )?lettelser", "mindske inflation)", "job igen", '(forsigtig|kontrolleret|gradvis)([a-zæåø ]{1,20})?(åbn|luk op|lukke op|opluk|åbn|gang|tilbag|op|øge|start)', '(åbn|luk op|lukke op|opluk|åbn|gang|tilbag|op|øge|start)([a-zæåø ]{1,20})?(forsigtig|kontrolleret|gradvis)',
                        '(se på|følg|fulgt|gøre som|gør som|efterlign|se hvad|spejl|a la|som|kig|mere)([a-zæåø ]{1,15})? sverige', 'sverige([a-zæåø ]{1,15})? eksempel'), collapse='|')
  protectionism <<- paste(c("(støtte|handle) dansk", "(støtte(|r)|hjælpe(|r)|køb(|e|er)|handl(|e|r)) (dansk|lokal)", "holde ferie","ferie (danmark|dk)", "handle(|r) lokalt", "dansk(e)? varer", "lokalt dansk", "lokale forretninger", "støtter lokalt",
                            "danske", "lukke (dk|danmark)", "problemer udefra", 'bliv([a-zæåø ]{1,15})? (danmark|dk)', 'danmark hjælpe sig selv', "grænse(|r|ne) lukke", "luk(ke)? grænserne", "styrke lokale", "varer lokalt", "danskproduce", "danske virksomheder", "fremmede arbejder hjem", "penge danmark", "lokale butikker", "skære import", "købe dansk(|e)", "støtte(|r) danske", "lokale virksomheder", "køb lokalt", "danske firmaer", "sommerferie (danmark|dk)", 
                            "mindske udenlandsk arbejdskraft", 'selv producer', '(danmark|dk) producer', 
                            'luk([a-zæåø ]{1,10}?)landet', '(stop|skær)([a-zæåø ]{1,10}?)import', 'ikke([a-zæåø ]{1,10})?ud af (land|danmark|dk)', "(køb|handel|handl|producer|forbrug|spender|bruge penge)([a-zæåø ]{1,15})? (dansk|lokal|indenland|indenrigs)",
                            'made in denmark', '(luk|stram|mindre|færre|stop|brems)([a-zæåø ]{1,15})? (indvandr|flygtning|immigrant|immegrant)'), collapse='|')
  
  tax_down <<- paste(c('((be)?skat|afgift|moms|grundskyld)([a-zæåø ]{1,20})?(eftergive|lav|sænk|reduc|fradrag|mindsk|nedsæt|udfas|stop|pause| sæt| let|fjern|favorabl|drop|lempe|udskyde|reduktion| ned |afskaf|fri|lavere)', # tax -- 
                       'skattereform', 'håndværkerfradrag', 'ingen skat', 'skattefrit', 'nul skat', 'skatterabat', 'uden skat', 'finanspolitik', 'skattestop', # ekstra words
                       '(eftergive|lav|sænk|reduc|fradrag|mindsk|nedsæt|udfas|stop|pause| sæt| let|fjern|favorabl|drop|lempe|udskyde|reduktion| ned |afskaf|fri|lavere)([a-zæåø ]{1,20})?((be)?skat|afgift|moms|grundskyld)', # -- tax
                       '(fradrag)([a-zæåø ]{1,20})?(hæv|stig|høj|øge|mere)', '(hæv|stig|høj|øge|mere)([a-zæåø ]{1,20})?(fradrag)'), collapse='|')
  helppackages <<- paste(c('(stat|offentlig|regering|politikere)([a-zæåø ]{1,20})?(holde hånden unde|sikre|hjælpe|støtte|invester|håndsrækning|pakke|stimulere|booste)', 'hjælpe[ ]{0,3}(pakke|program)',
                           'statsstøtte', 'nødpakke', "kapital indsprøjt", 'subsidi', 'støttepakke', '(løn|kompense)([a-zæåø ]{1,10}(kompensation|løn))?',
                           '(holde hånden unde|sikre|hjælp|støt|invester|håndsrækning|pakke|stimuler|boost|understøt|tildel|gang|kompenser|kompensation|support)([a-zæåø ]{1,20})?(produktion|selvstændig|landbrug|eksport|export|firma|arbejdsplads|sektor|restaurant|servicebranch|forretning|brancher|butik|erhverv|privat|virksomhed|industri|iværksæt|kultur)',
                           '(produktion|selvstændig|landbrug|eksport|export|firma|arbejdsplads|sektor|restaurant|servicebranch|forretning|brancher|butik|erhverv|privat|virksomhed|industri|iværksæt|kultur)([a-zæåø ]{1,20})?(holde hånden unde|sikre|hjælp|støt|invester|håndsrækning|pakke|stimuler|boost|understøt|tildel|gang|kompenser|kompensation|support)',
                           '(produktion|selvstændig|landbrug|eksport|export|firma|arbejdsplads|sektor|restaurant|servicebranch|forretning|brancher|butik|erhverv|privat|virksomhed|industri|iværksæt|kultur)([a-zæåø ]{1,10})?(igang|gang)',
                           'økonomisk (støtte|hjælp||kompensation)([a-zæåø ]{1,20}) (erhverv|virksomhed|arbejds|firma)'), collapse='|')
  cashtransfer <<- paste(c('borgerløn', 'feriepenge', 'sommercheck', 'helikopter[ ]{0,3}penge', 'helikopterpenge', 'udbetaling pensioner', ' su (sættes op|stige)', '(øge) su ', 'indefros'), collapse='|')
  publicspending <<- paste(c('(stat|offentlig|regering|politikere)([a-zæåø ]{1,20})?(anlæg|projekt|konstruktion|opgave|bygge|infrastruk)', 
                             'styrk([a-zæåø ]{1,10})?(velfærd|offentlige sektor)', 
                             'anlægs', '(bruge|spendere|investere)([a-zæåø ]{1,10})?(offentlige (penge|resurser|ressourcer|midler))',
                             '(invest|renover)([a-zæåø ]{1,10})?(offentlige|regionale|kommunale|folkeskol|sundhed|hospital|ældre|infrastrukt|bygge)',
                             "offentlige investeringer"), collapse='|')
  climate_invest <<- paste(c('bæredygtig', "grøn(|ne) (løsning|arbejdsplads|omstilling|projekt)", 'vedvarende (energi|sektor)', "klimavenlige", "klimainvesteringer", "klimaforbedringer", "grøn teknologi", "klimabelastning", "klimaforebyggende", "hensyn klimaet", 'gavne miljøet',
                             "greentech", "grønne tiltag", 'naturressourcer', "klimakrise", "klimaområdet", "fritage grønne", "naturens ressourcer", "klimabevidst", "evig vækst", "(forbrugs|penge)ræs", "klimaudfordring", "klimamål", "(tænke|nye) bæredygtig", "alternative løsninger", 
                             "klimaforbedringer", "ressourceforbrug", "klimafremmende", 'prioriter([a-zæåø ]{1,15})? klima',
                             '(klimaaftale|grøn(|ne)|bæredygtig)([a-z ]{1,20})?(energi|omstilling|klimaforandring)', 'invester([a-zæåø ]{1,20})? grøn'), collapse='|')
  non_avoidable <<- paste(c('svært undgå', "undgå for sent", 'allerede([a-zæåø ]{1,10})?krise', 'kan ingenting gøre', "uundgåelig", "desværre undgå", "tror desværre", "umulig([a-zæåø ]{1,30})?undgå", "krise undgå", "undgår økonomisk krise",
                            "tror([a-zæåø ]{1,10})?un(g)?dgå", 'vi få([a-zæåø ]{1,20})?krise', "undgå([a-zæåø ]{1,20})?(krise|næppe)", "danmark([a-zæåø ]{1,10})?langvarig", "ikke([a-zæåø ]{1,15})?undgå", "undgå([a-zæåø ]{1,15})?ikke", "undgå for sent", 'tror ikke kan', 'for sent'), collapse='|')
  tax_up <<- paste(c('((be)?skat|afgift|moms|grundskyld)([a-zæåø ]{1,20})?(hæv|stig|høj|inddrage|øge|mere|ekstra| op |forhøje)',
                     'corona[ ]{0,4}skat',
                     '(hæv|stig|høj|inddrage|øge|mere|ekstra| op |forhøje)([a-zæåø ]{1,20})?((be)?skat|afgift|moms|grundskyld)'), collapse='|')
  austerity <<- paste(c('lønreduktion', 'reduc([a-zæåø ]{1,10})?udbud([a-zæåø ]{1,10})?offentlig', '(lav|sænk|reduc|mindsk|nedsæt|reduktion|fjern|slank)([a-zæåø ]{1,20})?(offentlig|ydelse| su |kontanthjælp|dagpenge|børnepenge)', 
                        'reduktion([a-zæåø ]{1,10})?(offentlig|løn)', 'ansvarlig([a-zæåø ]{1,10})?(udgifter|indtægter)'), collapse='|')
  antipathy <<- paste(c('spekulation', 'multinationale', 'inddrag skat', 'skatteindrivelse', 'skattely', '(banker)([a-zæåø ]{1,20})?(sind )', 'svindel',
                        'store udenlandske virksomheder', 'grådige pengeinstitutter', '(fyr)([a-zæåø ]{1,20})?(ledere)', '(skat)([a-zæåø ]{1,20})?(inddrev|inddriv)', 'bank([a-zæåø ]{1,20})? give', 'bank([a-zæåø ]{1,20})? hjælp', 'pålæg([a-zæåø ]{1,10})? bank',
                        'bank([a-zæåø ]{1,10})? støt', 'bank([a-zæåø ]{1,10})? ansvar', 'bank([a-zæåø ]{1,30})? (samfundssind|samfundsind|samfund sind| samfunds sind)', 'bank([a-zæåø ]{1,30})? kontrol', 'kontrol([a-zæåø ]{1,20})? bank',
                        'bank([a-zæåø ]{1,10})? udnyt', 'krav([a-zæåø ]{1,20})? bank', 'stop([a-zæåø ]{1,20})? (udbyt|aktie|gevinst)'), collapse='|')
  interestrate <<- paste(c('(rente|banklån|rater|banker|lån)([a-zæåø ]{1,20})?(lav|sænk|reduc|mindsk|nedsæt|pause|fjern|favorab|drop|lempe|udskyde|reduktion|max|grænse|høje|ned|fair|stop|loft|rimelig|reguler|fasthold|løsne)', # interest rate --
                           '(lav|sænk|reduc|mindsk|nedsæt|pause|fjern|favorab|drop|lempe|udskyde|reduktion|max|grænse|høje|ned|fair|stop|loft|rimelig|reguler|hold|fasthold|løsne)([a-zæåø ]{1,20})?(rente|banklån|rate)', # -- interest rate
                           '(billig)([a-zæåø ]{1,10})?(lån)', '(ikke|forhindre|undgå|hæmme|stop|afværge)([a-zæåø ]{1,10})?(rentestigning)', 'udsætte gældsafvikling', 'rentepolitikken',
                           'ikke hæv renten', 'negative renter', 'minus( )?rente', 'rentefri', 'ågerrente', '(bank)([a-zæåø ]{1,10})?(skumme)', 'ingen renter', 'monetær politik', 'pengepolitik',
                           'lånemarkedet', 'erhvervslån', 'rentefri lån', 'lavrente',"lånefrihed", '(billig)([a-zæåø ]{1,10})?(lån)'), collapse='|')
  international_econ <<- paste(c('(hjælp|støt)([a-zæåø ]{1,15})?lande', 'stærk eksport', 'stærk export', 'verdensøkonomien', "åbne grænser", "krisen global","internationale relation", "gang eksporten", 'gang exporten', "arbejdskraft udlandet komme", "handel", "handelpartnere", "samhandel", "internationalt samarbejde", "samarbejde lande", 
                                 "resten verden", "eu samarbejd", "globalt plan", "globalisering", "lille økonomi", "hjælpe europæiske", "who", "gang turismen", "åben økonomi", 'omverdenen', 'hele verden', 'verdensplan', "afhæng([a-zæåø ]{1,20})? (export|eksport|verden|global|udland|international|lande)", "(samarbejd|afhængig)([a-zæåø ]{1,10})?(omverden|lande)", "globale økonomi", 
                                 "(afhængig(e)?|samarbejde) eu", "global(e)? verden", "hjælpe udlandet", "verdenssamfund", "verdensmarked", "exportmarkeder", '(global|international)([a-zæåø ]{1,20})? (krise|udfordring|økonomi|problem|handel|program|verden|samarbejd|fælles)', 'hele verden',
                                 'nordisk fællesskab', 'eksport'), collapse='|')
  bonds <<- paste(c('obligation', 'statslån', 'løbetid', 'købe aktier([a-zæåø ]{1,20})?(firmaer|industri|erhverv)'), collapse='|')
}
categories()

define_variables <- function(){
  survey$demand_econ <- ifelse(grepl(demand, survey$solution, perl=T), 1, 0)
  survey$classical_econ <- ifelse(grepl(classical, survey$solution, perl=T), 1, 0)
  survey$protect_econ <- ifelse(grepl(protectionism, survey$solution, perl=T), 1, 0)
  survey$health <- ifelse(grepl(health, survey$solution, perl=T), 1, 0)
  survey$dk_econ <- ifelse(grepl(DK, survey$solution, perl=T), 1, 0)
  # survey$authority <- ifelse(grepl(authority, survey$solution, perl=T), 1, 0)
  survey$international_econ <- ifelse(grepl(international_econ, survey$solution, perl=T), 1, 0)
  survey$non_avoidable <- ifelse(grepl(non_avoidable, survey$solution, perl=T), 1, 0)
  survey$climate_econ <- ifelse(grepl(climate, survey$solution, perl=T), 1, 0)
  survey$social <- ifelse(grepl(social, survey$solution, perl=T), 1, 0)
  survey$tax_down <- ifelse(grepl(tax_down, survey$solution, perl=T), 1, 0)
  survey$publicspending <- ifelse(grepl(publicspending, survey$solution, perl=T), 1, 0)
  survey$helppackages <- ifelse(grepl(helppackages, survey$solution), 1, 0)
  survey$cashtransfer <- ifelse(grepl(cashtransfer, survey$solution, perl=T), 1, 0)
  survey$austerity <- ifelse(grepl(austerity, survey$solution, perl=T), 1, 0)
  survey$tax_up <- ifelse(grepl(tax_up, survey$solution, perl=T), 1, 0)
  survey$interestrate <- ifelse(grepl(interestrate, survey$solution, perl=T), 1, 0)
  survey$bonds <- ifelse(grepl(bonds, survey$solution, perl=T), 1, 0)
  survey$antipathy <- ifelse(grepl(antipathy, survey$solution, perl=T), 1, 0)
  survey$coded <- NULL
  survey$coded <- ifelse(survey$demand_econ==0 & survey$classical_econ==0 & survey$protect_econ==0 & survey$health==0 & survey$dk_econ==0 & survey$authority==0 & survey$climate_econ ==0 & 
                         survey$social==0 & survey$international_econ==0 & survey$non_avoidable==0 & survey$tax_down==0 & helppackages==0 & cashtransfer==0 & publicspending==0 &
                         survey$tax_up==0 & survey$austerity==0 & survey$antipathy==0 & survey$interestrate==0 &  survey$bonds==0, 0, 1)
  survey$total_demand <- ifelse(survey$protect_econ==1 | survey$demand_econ==1 | survey$climate_econ==1 | survey$tax_down | publicspending==1 | 
                                survey$helppackages==1 | survey$bonds==1 | survey$interestrate==1 | survey$cashtransfer==1, 1, 0)
  survey[, classical_econ := ifelse(total_demand==0 & classical_econ==1, 1, 0)]
  survey$econ_answer <- NULL
  survey[, econ_answer := ifelse(demand_econ==1 | total_demand==1 | classical_econ==1 | international_econ==1 | protect_econ==1 | climate_econ==1 | tax_down==1 | tax_up==1 |
                                 publicspending==1 | helppackages==1 | cashtransfer==1 | austerity==1 | bonds==1 | interestrate==1 | non_avoidable==1, 1, ifelse(dk_econ==1, NA, 0))]
  
  
  survey$demand_econ_w1 <- ifelse(grepl(demand, survey$solution_w1, perl=T), 1, 0)
  survey$classical_econ_w1 <- ifelse(grepl(classical, survey$solution_w1, perl=T), 1, 0)
  survey$protect_econ_w1 <- ifelse(grepl(protectionism, survey$solution_w1, perl=T), 1, 0)
  survey$health_w1 <- ifelse(grepl(health, survey$solution_w1, perl=T), 1, 0)
  survey$dk_econ_w1 <- ifelse(grepl(DK, survey$solution_w1, perl=T), 1, 0)
  # survey$authority_w1 <- ifelse(grepl(authority, survey$solution_w1, perl=T), 1, 0)
  survey$international_econ_w1 <- ifelse(grepl(international_econ, survey$solution_w1, perl=T), 1, 0)
  survey$non_avoidable_w1 <- ifelse(grepl(non_avoidable, survey$solution_w1, perl=T), 1, 0)
  survey$climate_econ_w1 <- ifelse(grepl(climate, survey$solution_w1, perl=T), 1, 0)
  survey$social_w1 <- ifelse(grepl(social, survey$solution_w1, perl=T), 1, 0)
  survey$tax_down_w1 <- ifelse(grepl(tax_down, survey$solution_w1, perl=T), 1, 0)
  survey$publicspending_w1 <- ifelse(grepl(publicspending, survey$solution_w1, perl=T), 1, 0)
  survey$helppackages_w1 <- ifelse(grepl(helppackages, survey$solution_w1), 1, 0)
  survey$cashtransfer_w1 <- ifelse(grepl(cashtransfer, survey$solution_w1, perl=T), 1, 0)
  survey$austerity_w1 <- ifelse(grepl(austerity, survey$solution_w1, perl=T), 1, 0)
  survey$tax_up_w1 <- ifelse(grepl(tax_up, survey$solution_w1, perl=T), 1, 0)
  survey$interestrate_w1 <- ifelse(grepl(interestrate, survey$solution_w1, perl=T), 1, 0)
  survey$bonds_w1 <- ifelse(grepl(bonds, survey$solution_w1, perl=T), 1, 0)
  survey$antipathy_w1 <- ifelse(grepl(antipathy, survey$solution_w1, perl=T), 1, 0)
  survey$coded_w1 <- NULL
  survey$coded_w1 <- ifelse(survey$demand_econ_w1==0 & survey$classical_econ_w1==0 & survey$protect_econ_w1==0 & survey$health_w1==0 & survey$dk_econ_w1==0 & survey$authority_w1==0 & survey$climate_econ_w1 ==0 & 
                            survey$social_w1==0 & survey$international_econ_w1==0 & survey$non_avoidable_w1==0 & survey$tax_down_w1==0 & survey$helppackages_w1==0 & survey$cashtransfer_w1==0 & survey$publicspending_w1==0 &
                            survey$tax_up_w1==0 & survey$austerity_w1==0 & survey$antipathy_w1==0 & survey$interestrat_w1==0 &  survey$bonds_w1==0, 0, 1)
  survey$total_demand_w1 <- ifelse(survey$protect_econ_w1==1 | survey$demand_econ_w1==1 | survey$climate_econ_w1==1 | survey$tax_down_w1 | survey$publicspending_w1==1 | 
                                   survey$helppackages_w1==1 | survey$bonds_w1==1 | survey$interestrate_w1==1 | survey$cashtransfer_w1==1, 1, 0)
  survey[, classical_econ_w1 := ifelse(total_demand_w1==0 & classical_econ_w1==1, 1, 0)]
  survey$econ_answer_w1 <- NULL
  survey[, econ_answer_w1 := ifelse(demand_econ_w1==1 | total_demand_w1==1 | classical_econ_w1==1 | international_econ_w1==1 | protect_econ_w1==1 | climate_econ_w1==1 | tax_down_w1==1 | tax_up==1 |
                                    publicspending_w1==1 | helppackages_w1==1 | cashtransfer_w1==1 | austerity_w1==1 | bonds_w1==1 | interestrate_w1==1 | non_avoidable==1, 1, ifelse(dk_econ_w1==1, NA, 0))]
  survey <<- survey
  
}
define_variables()


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# BACKGROUND VARIABLES 
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

survey <- setDT(survey %>% mutate(
  party = case_when(q10==1~'Socialdemokratiet', q10==2~'Radikale Venstre', q10==3~'Det Konservative Folkeparty', 
                    q10==4~'Nye Borgerlige', q10==5~'Socialistisk Folkeparti', q10==6~'Liberal Alliance', q10==7~'Kristendemokraterne', 
                    q10==8~'Dansk Folkeparti', q10==9~'Stram Kurs', q10==10~'Venstre', q10==11~'Enhedslisten', q10==12~'Alternativet', 
                    q10 %in% c(13:17)~'Other')))
survey[, ideology := ifelse(q10 %in% c(1, 2, 5, 11, 12), 'Left', ifelse(q10 %in% c(3, 4, 6, 7, 8, 9, 10), 'Right', NA))]
survey[, employment := ifelse(q2 %in% c(1, 2), 'Employed', ifelse(q2 %in% c(3), 'Student', ifelse(q2 %in% c(4, 5, 6), 'Not employed', NA)))]
survey[, unemployment := ifelse(employment=='Not employed', 1, 0)]
survey[, education := ifelse(q1==1, 'Elementary', ifelse(q1 %in% 2:3, 'High school', ifelse(q1==4, 'Vocational', ifelse(q1==5, 'Higher (short)', ifelse(q1==6, 'Higher (medium)', ifelse(q1==7, 'Higher (long)', ifelse(q1==8, 'Doctorate', NA)))))))]
survey[, intervention := ifelse(total_demand==1 & classical_econ==0, 0, ifelse(total_demand==0 & classical_econ==1, 1, NA))]
survey[, intervention_w1 := ifelse(total_demand_w1==1 & classical_econ_w1==0, 0, ifelse(total_demand_w1==0 & classical_econ_w1==1, 1, NA))]
survey[, protect := ifelse(protect_econ==1 & international_econ==0, 1, ifelse(protect_econ==0 & international_econ==1, -1, ifelse(protect_econ==1 & international_econ==1, 0, NA)))]
survey[, incumbent := ifelse(party=='Socialdemokratiet', 'Support incumbent', 'Support non-incumbent')]
survey[q12b_2_resp!=99, politicians_correct := q12b_2_resp]
survey[q13!=99, trust_politicians := q13]
survey[q14!=99, globalization := q14]
survey[, koen_num := ifelse(c_Koen=='Kvinde', 1, 0)]
survey[, gender := ifelse(c_Koen=='Kvinde', 'Female', 'Male')]
survey[ , SendDate := as.Date(c_SendDate, format='%Y-%m-%d')]
survey[ , starttime := as.Date(W2_FinishTime, format='%Y-%m-%d')]
survey[ , c_RemindDate1 := as.Date(c_RemindDate1, format='%Y-%m-%d')]
survey[ , c_RemindDate2 := as.Date(c_RemindDate2, format='%Y-%m-%d')]
survey[, both_w1 := ifelse(total_demand_w1==1 & classical_econ_w1 ==1, 1, 0)]
survey[, both := ifelse(total_demand==1 & classical_econ_w1 ==1, 1, 0)]

survey[q12a_1_resp==11, q12a_1_resp := NA]
sort <- survey[, mean(q12a_1_resp, na.rm=T), by='party']
survey[ , coalition := ifelse(party %in% c('Alternativet', 'Enhedslisten', 'Socialistisk Folkeparti', 'Radikale Venstre', 'Socialdemokratiet'), 
                                   'Ideological\nleft', 'Ideological\nright')]

survey[!is.na(intervention_w1), intervention2_w1 := ifelse(intervention_w1==1, 0, 1)]
survey[!is.na(intervention), intervention2_w2 := ifelse(intervention==1, 0, 1)]

survey[, within_demand := total_demand - total_demand_w1]
survey[, within_classical := classical_econ - classical_econ_w1]

first_wave <- as.Date("2020-04-03")
second_wave <- as.Date("2020-06-15")


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# NUMBERS IN TEXT
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

# SAMPLE SIZE
nrow(survey) #  12131

# Respondents in the first week of April
survey[FinishTime<"2020-04-06", .N] / survey[!is.na(FinishTime), .N] # 0.58



# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 1A
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

names(business_trust) <- c('date', 'Business-trust indicator')
business_trust[, date := as.Date(paste(gsub('M', '-', date), '15', sep='-'))]
business_trust[, outcome := 'Business-trust indicator']

business <- ggplot(business_trust[date>as.Date("2008-04-15")], aes(x=date, y=`Business-trust indicator`, group=outcome)) + geom_line() + 
  ylab("") + xlab("") + facet_wrap(~outcome) + scale_x_date(limits=c(min(business_trust$date), max(business_trust$date))) +
  geom_point(size=3, color='black') + geom_point(size=2, color='white') + theme_bw() + geom_vline(xintercept = first_wave, col='red')+
  geom_vline(xintercept = second_wave, col='red') + 
  theme(axis.text = element_text(size=20), strip.text = element_text(size=25), strip.background =element_rect(fill="white"))
business

#ggsave(file='Plots/business_trust.pdf', business, width = 8, height = 5, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 1B
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
names(consume) <- c('date', 'Consumer-trust indicator')
consume[, date := as.Date(paste(gsub('M', '-', date), '15', sep='-'))]
consume[, outcome := 'Consumer-trust indicator']

consum <- ggplot(consume[date>as.Date("2008-04-15")], aes(x=date, y=`Consumer-trust indicator`, group = outcome)) + geom_line() + 
  ylab("") + xlab("") + facet_wrap(~outcome) + scale_x_date(limits=c(min(consume$date), max(consume$date))) +
  geom_point(size=3, color='black') + geom_point(size=2, color='white') + theme_bw() + geom_vline(xintercept = first_wave, col='red')+
  geom_vline(xintercept = second_wave, col='red') + 
  theme(axis.text = element_text(size=20), strip.text = element_text(size=25), strip.background =element_rect(fill="white"))
consum

#ggsave(file='Plots/consum.pdf', consum, width = 8, height = 5, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 1C
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

names(GDP) <- c('date', 'GDP, pct. growth (seasonally corrected)')
GDP[, outcome := 'GDP, pct. growth (seasonally corrected)']

GDP_plot <- ggplot(GDP, aes(x=date, y=`GDP, pct. growth (seasonally corrected)`, group=outcome)) + 
  geom_line(col='black') + 
  ylab("Pct.") + xlab("") + facet_wrap(~outcome) +
  geom_point(size=3, color='black') + geom_point(size=2, color='white') + theme_bw() +
  theme(axis.title.y = element_text(size=20), axis.text.y = element_text(size=20), axis.text.x = element_text(size=20, angle = 45, hjust=1), strip.text = element_text(size=25), strip.background =element_rect(fill="white"))
GDP_plot

#ggsave(file='Plots/gdp.pdf', GDP_plot, width = 8, height = 5, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 1D
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

names(employed) <- c('date', 'Number of unemployed (Pct. of total workforce)')
employed[, outcome := 'Number of unemployed (Pct. of workforce)']
employed[, date := as.Date(paste(gsub('M', '-', date), '15', sep='-'))]

employed_plot <- ggplot(employed, aes(x=date, y=`Number of unemployed (Pct. of total workforce)`, group=outcome)) + 
  geom_line(col='black') + 
  ylab("") + xlab("") + facet_wrap(~outcome) +
  geom_vline(xintercept = first_wave, col='red')+
  geom_vline(xintercept = second_wave, col='red') + 
  geom_point(size=3, color='black') + geom_point(size=2, color='white') + theme_bw() +
  theme(axis.title.y = element_text(size=20), axis.text.y = element_text(size=20), axis.text.x = element_text(size=20, angle = 45, hjust=1), strip.text = element_text(size=25), strip.background =element_rect(fill="white"))
employed_plot

#ggsave(file='Plots/employed.pdf', employed_plot, width = 8, height = 5, dpi = 1200)



# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 2
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

survey[, solution_stem := sapply(solution, function(x){paste(unlist(text_tokens(x, stemmer='da')), collapse=' ')})]
survey[, solution_w1_stem := sapply(solution_w1, function(x){paste(unlist(text_tokens(x, stemmer='da')), collapse=' ')})]

ngram_fct <- function(x){
  none_grams <- lapply(x, function(x){data.frame(bigram = names(x), number=x)})
  none_grams <- setDT(rbindlist(none_grams, fill = T))
  none_grams <- none_grams[, sum(number), by='bigram']
  none_grams[, bigram := gsub('_', ' ', bigram)]
  none_grams <- none_grams[str_count(bigram)>7]
  setorder(none_grams, -V1)
  none_grams[, order := -(1:nrow(none_grams))]
}

top_ngram <- sapply(survey[, solution_stem], function(x){topfeatures(dfm(tokens_ngrams(tokens_remove(tokens(x, remove_symbols = TRUE, remove_punct = TRUE, remove_numbers = TRUE), 
                                                                                                          pattern=stopwords), n = 2)))})
top_ngram <-  ngram_fct(top_ngram); fwrite(top_ngram, '/Users/anderswoller/Dropbox/Studentermedhjælpere/Anders/COVID19 econ/top_ngram.csv')
top_plot2 <- top_ngram[1:25]
top_plot2$wave <- 'Wave two'
top_ngram <- sapply(survey[, solution_w1_stem], function(x){topfeatures(dfm(tokens_ngrams(tokens_remove(tokens(x, remove_symbols = TRUE, remove_punct = TRUE, remove_numbers = TRUE), 
                                                                                                             pattern=stopwords), n = 2)))})
top_ngram <-  ngram_fct(top_ngram); fwrite(top_ngram, '/Users/anderswoller/Dropbox/Studentermedhjælpere/Anders/COVID19 econ/top_ngram2.csv')
top_plot1 <- top_ngram[1:25]
top_plot1$wave <- 'Wave one' 

english1 = c('Quick possible', 'Open society', 'Economic crisis', 'Non avoidable', 'Spend money', 
             'Buy Danish', 'Slowly open', 'Society open', 'Get started',
             'Open society', 'Slowly calmly', 'Opening society', 'Keep distance', 'Open country', 'Wheels turning', 'Public investments', 'Don\'t think', 
             'Have vacation [in Denmark]','Economic support', 'Vacation Denmark', 'Helping hand', 'Open Denmark', 'Gradual opening', 'Support packages', 'Society quickly')
english2 = c('Spend money', 'Green transformation', 'Get started', 'Buy Danish', 'Public Investments', 'Frozen holiday money', 'Danish economy', 
             'Economic policy', 'Wheels turning', 'Boost consumption', 'lower VAT', 'Quick possible', 'Kickstart economy', 'Expansive fiscal policy', 'Support packages',
             'Helping hand', 'Reduce VAT', 'Economic support', 'Danish business', 'Pay tax', 'Adjust tax', 'Money Denmark', 'Public sector', 'Have vacation [in Denmark]', 'Decrease VAT')


# ******** WAVE 1 ********
top_word1 <- ggplot(data=top_plot1, aes(x=order, y=V1)) + geom_histogram(stat = 'identity', alpha=.6, width=.5, fill='white', col='black') + coord_flip() + theme_bw() + 
  scale_x_continuous(breaks=top_plot1$order, label=english1) + ylab('Respondents') + xlab('') + facet_wrap(~wave) + scale_y_continuous(limits=c(0, 600)) +
  theme(axis.text.y = element_text(hjust = 0), 
        panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(), panel.grid.minor.x = element_blank(), strip.text = element_text(size=15))
top_word1
#ggsave(file='Plots/top_word_plot1.pdf', top_word1, width = 3.5, height = 4.5, dpi = 1200)


# ******** WAVE 2 ********
top_word2 <- ggplot(data=top_plot2, aes(x=order, y=V1)) + geom_histogram(stat = 'identity', alpha=.6, width=.5, fill='white', col='black') + coord_flip() + theme_bw() + 
  scale_x_continuous(breaks=top_plot2$order, labels = english2) + ylab('Respondents') + xlab('') + facet_wrap(~wave) + scale_y_continuous(limits=c(0,600)) +
  theme(axis.text.y = element_text(hjust = 0), panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(), panel.grid.minor.x = element_blank(), strip.text = element_text(size=15))
top_word2
#ggsave(file='Plots/top_word_plot2.pdf', top_word2, width = 3.5, height = 4.5, dpi = 1200)



# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 3A
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

aggregate_sum <- function(x, round){ 
  if(round==2){setDT(data.frame(topic = c('Economic answer', 'Crisis unavoidable', "Don\'t know", 'Health measures', 'Non-state solutions', 'Antipathy'), 
                                group = c(1, 6, 6, 7,7,7),
                                total = nrow(x),
                                sum = t(x[, list(sum(econ_answer, na.rm=T), 
                                                 sum(non_avoidable),sum(dk_econ), sum(health), sum(social), sum(antipathy))]), 
                                sd = t(x[, list(sd(econ_answer, na.rm=T),
                                                sd(non_avoidable), sd(dk_econ), sd(health), sd(social), sd(antipathy))])))}else{
                                                  setDT(data.frame(topic = c('Economic answer', 'Crisis unavoidable', "Don\'t know", 'Health measures', 'Non-state solutions', 'Antipathy'), 
                                                                   group = c(1, 6, 6, 7,7,7),
                                                                   total = nrow(x),
                                                                   sum = t(x[, list(sum(econ_answer_w1, na.rm=T), 
                                                                                    sum(non_avoidable_w1),sum(dk_econ_w1), sum(health_w1), sum(social_w1), sum(antipathy_w1))]), 
                                                                   sd = t(x[, list(sd(econ_answer_w1, na.rm=T),
                                                                                   sd(non_avoidable_w1), sd(dk_econ_w1), sd(health_w1), sd(social_w1), sd(antipathy_w1))])))}}
dict_dta <- aggregate_sum(survey, round=1)
dict_dta[, wave := 'Wave 1']
dict_survey <- aggregate_sum(survey, round=2)
dict_survey[, wave := 'Wave 2']
dict_dta <- rbind(dict_dta, dict_survey)
dict_dta[, error := sd / sqrt(total)]
dict_dta[, group := as.factor(group)]
dict_dta[, sum_pct := sum / total]
dict_dta[, topic := factor(topic, levels=c('Economic answer', 'Crisis unavoidable', "Don\'t know", 'Health measures', 'Non-state solutions', 'Antipathy'))]

dict_dta[ , sum(sum), by='wave']

dict_plot <- ggplot(data=dict_dta, aes(x=topic, y=sum_pct, fill=wave, ymin=sum_pct-1.96*error, ymax=sum_pct+1.96*error)) + 
  geom_bar(position=position_dodge2(), stat="identity", alpha=.8) + xlab('') + theme_bw() +
  scale_y_continuous(minor_breaks = seq(0, 1, .025), breaks=seq(0, 1, 0.05),
                     label=scales::percent_format(accuracy = 1)) + ylab('Percent of answers') + 
  geom_errorbar(lwd=1, position=position_dodge2(.9, padding=.8)) + 
  theme(axis.text.x = element_text(angle = 15, hjust=1), legend.position = 'top', legend.title = element_blank(), strip.text = element_text(size=20), strip.background =element_rect(fill="white"),
        panel.grid.major.x = element_blank(), axis.text=element_text(size=13), legend.text=element_text(size=20),axis.title=element_text(size=15), panel.grid.minor.x = element_blank()) + 
  scale_fill_manual(values=c('black', 'gray40'))
dict_plot

#ggsave(file='Plots/dict_plot.pdf', dict_plot, width = 8, height = 6, dpi = 1200)

# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 3B
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

aggregate_sum <- function(x, round){ 
  if(round==2){setDT(data.frame(topic = c('Non-intervention', 
                                          'Intervention', 
                                          'Business support packages', 'Climate investments', 'Tax reductions', 'Direct cash transfers', 'Public spending', 'Interest rate', 'Bonds', 
                                          'International collaboration', 'Country specific investments', 'Increased taxes', 'Austerity'), 
                                group = c(1, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5),
                                total = nrow(x),
                                sum = t(x[, list(sum(classical_econ), sum(total_demand),
                                                 sum(helppackages), sum(tax_down), sum(climate_econ), sum(cashtransfer), sum(publicspending), sum(interestrate), sum(bonds), sum(international_econ), sum(protect_econ), sum(tax_up), sum(austerity))]), 
                                sd = t(x[, list(sd(classical_econ), sd(total_demand),
                                                sd(helppackages), sd(tax_down), sd(climate_econ), sd(cashtransfer), sd(publicspending), sd(interestrate), sd(bonds), sd(international_econ), sd(protect_econ), sd(tax_up), sd(austerity))])))}else{
                                                  setDT(data.frame(topic = c('Non-intervention', 
                                                                             'Intervention', 
                                                                             'Business support packages', 'Climate investments', 'Tax reductions', 'Direct cash transfers', 'Public spending', 'Interest rate', 'Bonds', 
                                                                             'International collaboration', 'Country specific investments', 'Increased taxes', 'Austerity'), 
                                                                   group = c(1, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5),
                                                                   total = nrow(x),
                                                                   sum = t(x[, list(sum(classical_econ_w1), sum(total_demand_w1),
                                                                                    sum(helppackages_w1), sum(tax_down_w1), sum(climate_econ_w1), sum(cashtransfer_w1), sum(publicspending_w1), sum(interestrate_w1), sum(bonds_w1), sum(international_econ_w1), sum(protect_econ_w1), sum(tax_up_w1), sum(austerity_w1))]), 
                                                                   sd = t(x[, list(sd(classical_econ_w1), sd(total_demand_w1),
                                                                                   sd(helppackages_w1), sd(tax_down_w1), sd(climate_econ_w1), sd(cashtransfer_w1), sd(publicspending_w1), sd(interestrate_w1), sd(bonds_w1), sd(international_econ_w1), sd(protect_econ_w1), sd(tax_up_w1), sd(austerity_w1))])))}}

dict_dta <- aggregate_sum(survey[econ_answer_w1==1], round=1) # obs: depending on R1 second comment change here: add "econ_answer_w1==1 & econ_answer==1" to both
dict_dta[, wave := 'Wave 1']
dict_survey <- aggregate_sum(survey[econ_answer==1], round=2) # obs: depending on R1 second comment change here: add "econ_answer_w1==1 & econ_answer==1" to both
dict_survey[, wave := 'Wave 2']
dict_dta <- rbind(dict_dta, dict_survey); rm(dict_survey)
dict_dta[, error := sd / sqrt(total)]
dict_dta[, group := as.factor(group)]
dict_dta[, sum_pct := sum / total]
dict_dta[, sort := max(sum_pct), by='topic']
setorder(dict_dta, sort, wave)
dict_dta[, overall := ifelse(topic %in% c('Intervention', 'Non-intervention'), 'Overall categories', 'Intervention disaggregated')]
dict_dta[, overall := factor(overall, levels=c('Overall categories', 'Intervention disaggregated'))]
dict_dta[, topic := factor(topic, levels=c('Non-intervention', 'Intervention', 'Business support packages', 'Climate investments',
                                           'Country specific investments', 'Direct cash transfers', 'Tax reductions', 'Public spending', 'International collaboration', 
                                           'Interest rate', 'Bonds', 'Increased taxes', 'Austerity'))]
dict_dta[ , sum(sum), by='wave']
dict_dta[sum_pct>.05, uniqueN(topic)]

dict_plot2 <- ggplot(data=dict_dta, aes(x=topic, y=sum_pct, fill=wave, ymin=sum_pct-1.96*error, ymax=sum_pct+1.96*error)) + 
  geom_bar(position=position_dodge2(), stat="identity", alpha=.8) + facet_wrap(~overall, scales = 'free_x') + xlab('') + 
  theme_bw() + scale_y_continuous(limits=c(0,1), minor_breaks = seq(0, 1, .025), breaks=seq(0, 1, 0.1), label=scales::percent_format(accuracy = 1)) + ylab('Percent of answers') + 
  geom_errorbar(lwd=1, position=position_dodge2(.9, padding=.8)) + 
  theme(axis.text.x = element_text(angle = 45, hjust=1), legend.position = 'none', legend.title = element_blank(), strip.text = element_text(size=20), strip.background =element_rect(fill="white"),
        panel.grid.major.x = element_blank(), axis.text=element_text(size=13), axis.title=element_text(size=15), panel.grid.minor.x = element_blank()) + 
  scale_fill_manual(values=c('black', 'gray40'))
dict_plot2

#ggsave(file='Plots/dict_plot2.pdf', dict_plot2, width = 8, height = 6, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 4A
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

wave1 <- survey[econ_answer==1, list(mean(intervention2_w1, na.rm=T), sd(intervention2_w1, na.rm=T), .N), by='party'][, wave := 'Wave one']
wave2 <- survey[econ_answer==1, list(mean(intervention2_w2, na.rm=T), sd(intervention2_w2, na.rm=T), .N), by='party'][, wave := 'Wave two']
partychange <- rbind(wave1, wave2)

partychange[, party := factor(party, levels=c('Enhedslisten', 'Socialistisk Folkeparti', 'Alternativet', 
                                              'Socialdemokratiet', 'Radikale Venstre', 'Dansk Folkeparti', 
                                              'Venstre', 'Det Konservative Folkeparty', 'Nye Borgerlige', 
                                              'Liberal Alliance'))]
partychange[ , coalition := ifelse(party %in% c('Alternativet', 'Enhedslisten', 'Socialistisk Folkeparti', 'Radikale Venstre', 'Socialdemokratiet'), 
                              'Ideological\nleft', 'Ideological\nright')]

partychange <- partychange[!is.na(party)]

english = c('Unity List', 'Socialist People\'s Party', 'The Alternative', 'Social Democrats', 'Social Liberal Party', 'Danish People\'s Party', 'Liberal Party', 'The Conservative People\'s Party', 
            'New Right', 'The Liberal Alliance')

party_plot <- ggplot(partychange, aes(x=party, y=V1, col=coalition, alpha=as.factor(wave), 
                                      ymax=V1+1.96*(V2/sqrt(N)), ymin=V1-1.96*(V2/sqrt(N)))) +
  coord_flip() + theme_bw() + xlab("") + ylab('Support for intervention (1) vs. non-intervention (0)') +
  scale_y_continuous(limits=c(0, 1.05), breaks=seq(0, 1, 0.1), minor_breaks = seq(-2, 2, .1)) + 
  geom_errorbar(width=.3, lwd=1.3) + scale_x_discrete(labels=english) + 
  geom_point(size=4, col='white', alpha=1) + geom_point(size=4) +
  scale_color_manual('Parties sorted by right-\nleft position', values=c('firebrick', 'dodgerblue4')) +  scale_alpha_discrete('', range=c(.2, .8), c('Wave one', 'Wave two')) +  
  theme(legend.title = element_text(size = 15), legend.position = 'top', axis.title = element_text(size=15), axis.text = element_text(size=15), 
        legend.text = element_text(size=15))
party_plot

#ggsave(file='Plots/party_plot.pdf', party_plot, width = 12, height = 5, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 4B
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

survey[ , c_SendDate := as.Date(c_SendDate, format='%Y-%m-%d')]
survey[ , StartTime := as.Date(StartTime, format='%Y-%m-%d')]
survey[, week := format(c_SendDate, "%W")]
survey[, week_w1 := format(StartTime, "%W")]
wave1 <- survey[econ_answer==1, list(mean(intervention2_w1, na.rm=T), sd(intervention2_w1, na.rm=T), .N, median(StartTime)), by=c('ideology', 'week_w1')][, c('wave') := 'Wave one']
wave2 <- survey[econ_answer==1, list(mean(intervention2_w2, na.rm=T), sd(intervention2_w2, na.rm=T), .N, median(c_SendDate)), by=c('ideology', 'week')][, wave := 'Wave two']
names(wave1)[names(wave1)=='week_w1'] <- 'week'
wave1 <- wave1[, .SD, .SDcols=sort(colnames(wave1))]
wave2 <- wave2[, .SD, .SDcols=sort(colnames(wave2))]
convergence_dta <- rbind(wave1, wave2)
convergence_dta[, sderror := V2 / sqrt(N)]
convergence_dta <- convergence_dta[!is.na(ideology)]
convergence_dta[, V4 := as.Date(V4)]
convergence_dta <- convergence_dta[N>50]
extra <- convergence_dta[c(1,20)]; extra[, c('V4', 'V1', 'N') := list(c(as.Date("2020-03-31"), as.Date("2020-06-15")), c(NA,NA), c(NA,NA))]
convergence_dta <- rbind(convergence_dta, extra)

name = c('Wave one', 'Wave two (randomized re-invitation date)')
names(name) <- c('Wave one', 'Wave two')

convergence_plot <- ggplot(data=convergence_dta, 
                           aes(x=V4, y=V1, ymin=V1-1.96*sderror, ymax=V1+1.96*sderror, group=ideology, col=ideology)) + 
  theme_bw() + geom_errorbar(width=0, lwd=1.3, alpha=.7) + 
  geom_point(size=4, col='white', alpha=1) + geom_point(size=4, alpha=.7) +
  scale_y_continuous(limits=c(0,1), breaks=seq(0, 1, .1)) +
  xlab('Response week') + 
  scale_color_manual(labels=c('Ideological right', 'Ideological left'), values=c('firebrick', 'dodgerblue4')) +
  ylab('Intervention support') + facet_grid(~wave, scales = "free_x", space="free_x", labeller=labeller(wave=name)) +
  theme(axis.text.x = element_text(size=15), axis.text.y = element_text(size=10),
        panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank(),
        axis.title = element_text(size=15), legend.text = element_text(size=15),
        legend.title = element_blank(), legend.position = 'bottom',
        strip.text = element_text(size=15), strip.background = element_rect(fill="white"), plot.margin=unit(c(0,0,-1,0), "cm"))
convergence_plot

dist_plot <- ggplot(data=convergence_dta, aes(x=V4, y=N, group=ideology, fill=ideology)) + theme_bw() +
  theme(line = element_blank(),  text = element_blank(), title = element_blank(), legend.position = 'none', 
        panel.border = element_blank(), plot.margin=unit(c(0,0,0,0), "cm")) +
  geom_bar( position='dodge', stat='identity', alpha=.7, width=2) + facet_grid(~wave, scales = "free_x", space="free_x") + 
  scale_fill_manual(labels=c('Ideological right', 'Ideological left'), values=c('firebrick', 'dodgerblue4')) + ylab('')
dist_plot

convergence_plot <- grid.arrange(dist_plot, convergence_plot, ncol=1,  layout_matrix = rbind(c(NA, rep(1,24)),
                                                                                             c(2, 2, 2), c(2, 2, 2), c(2, 2, 2),
                                                                                             c(2, 2, 2), c(2, 2, 2), c(2, 2, 2)))
#ggsave(file='Plots/convergence_plot.pdf', convergence_plot, width = 10, height = 6, dpi = 1200)

# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 5
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

helppackages <- survey[econ_answer==1, list(mean(helppackages, na.rm=T), sd(helppackages, na.rm=T), .N), by='ideology'][, outcome := 'Business support packages']
climate_econ <- survey[econ_answer==1, list(mean(climate_econ, na.rm=T), sd(climate_econ, na.rm=T), .N), by='ideology'][, outcome := 'Climate investments']
tax_down <- survey[econ_answer==1, list(mean(tax_down, na.rm=T), sd(tax_down, na.rm=T), .N), by='ideology'][, outcome := 'Tax reductions']
publicspending <- survey[econ_answer==1, list(mean(publicspending, na.rm=T), sd(publicspending, na.rm=T), .N), by='ideology'][, outcome := 'Public investments']
cashtransfer <- survey[econ_answer==1, list(mean(cashtransfer, na.rm=T), sd(cashtransfer, na.rm=T), .N), by='ideology'][, outcome := 'Direct cash transfers']

subcategories <- rbind(helppackages, climate_econ, tax_down, publicspending, cashtransfer)
subcategories <- subcategories[!is.na(ideology)]; rm(helppackages, climate_econ, tax_down, publicspending, cashtransfer)
subcategories[, wave := 'Wave two']

helppackages <- survey[econ_answer==1, list(mean(helppackages_w1, na.rm=T), sd(helppackages_w1, na.rm=T), .N), by='ideology'][, outcome := 'Business support packages']
climate_econ <- survey[econ_answer==1, list(mean(climate_econ_w1, na.rm=T), sd(climate_econ, na.rm=T), .N), by='ideology'][, outcome := 'Climate investments']
tax_down <- survey[econ_answer==1, list(mean(tax_down_w1, na.rm=T), sd(tax_down_w1, na.rm=T), .N), by='ideology'][, outcome := 'Tax reductions']
publicspending <- survey[econ_answer==1, list(mean(publicspending_w1, na.rm=T), sd(publicspending_w1, na.rm=T), .N), by='ideology'][, outcome := 'Public investments']
cashtransfer <- survey[econ_answer==1, list(mean(cashtransfer_w1, na.rm=T), sd(cashtransfer_w1, na.rm=T), .N), by='ideology'][, outcome := 'Direct cash transfers']
subcategories_w1 <- rbind(helppackages, climate_econ, tax_down, publicspending, cashtransfer)
subcategories_w1 <- subcategories_w1[!is.na(ideology)]; rm(helppackages, climate_econ, tax_down, publicspending, cashtransfer)
subcategories_w1[, wave := 'Wave one']
subcategories <- rbind(subcategories, subcategories_w1)

subcategories[, outcome := factor(outcome, levels=c('Business support packages', 'Tax reductions', 
                                                    'Direct cash transfers', 'Public investments', 
                                                    'Climate investments'))]

subcat_plot <- ggplot(subcategories, aes(x=outcome, y=V1, ymin=V1-1.96*(V2/sqrt(N)), ymax=V1+1.96*(V2/sqrt(N)), color=ideology, alpha=as.factor(wave))) + 
  theme_bw() + geom_errorbar(width=0, lwd=1.3) + theme(legend.title = element_text(size = 15), 
                                                       legend.position = 'top', axis.title = element_text(size=15), axis.text = element_text(size=15), 
                                                       legend.text = element_text(size=15)) + scale_y_continuous(limits=c(0,.45)) +
  scale_color_manual('', labels=c('Ideological left', 'Ideological right'), values=c('firebrick', 'dodgerblue4')) +
  scale_alpha_discrete(' Survey', range=c(.2, .8), c('Wave one', 'Wave two')) +
  geom_point(size=4, col='white', alpha=1) + geom_point(size=4)  + coord_flip() + xlab('') + ylab('Average support')
subcat_plot

#ggsave(file='Plots/subcat_plot.pdf', subcat_plot, width = 12, height = 4, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# APPENDIX
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 6
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
compliance_dta <- survey[, .SD, .SDcols=c('starttime', 'SendDate', 'c_RemindDate1', 'c_RemindDate2')]
compliance_dta[, SendDate_std := starttime - SendDate]

compliance <- ggplot(data=compliance_dta, aes(x=as.numeric(SendDate_std))) + geom_histogram(fill='black', color='black', alpha=.2) + 
  theme_bw() + xlab('Days from first re-invitation') + theme(axis.text.x = element_text(angle=45, hjust=1)) + 
  scale_x_continuous(limits=c(-2,30), breaks=0:30, labels=c('Re-invitation', 1:3, '1st Reminder', 5:8, '2nd Reminder', 10:30))
compliance

#ggsave(file='Plots/compliance.pdf', compliance, width = 8, height = 5.5, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 7
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

variable <- c('classical_econ', 'total_demand', 'helppackages', 'publicspending', 'cashtransfer', 'tax_down', 'bonds', 'interestrate')
name <- c('Non-intervention', 'Intervention', 'Business support packages', 'Public spending', 'Direct cash transfers', 'Tax reductions', 'Bonds', 'Interest rate')
names(name) <- variable

quality <- NULL
for (i in variable){
  quality <- rbind(quality, data.frame(solution = survey[survey[[i]]==1][['Q27']], outcome = i, wave='Wave two'))
  dta_loop <- data.frame(solution_w1 = survey[survey[[paste(i, '_w1', sep='')]]==1][['Q20_text']], outcome = i, wave='Wave one')
  names(dta_loop) <- c('solution', 'outcome', 'wave')
  quality <- rbind(quality, dta_loop)}
setDT(quality)[ , length := str_count(solution, ' ')]

quality_plot <- ggplot(quality, aes(x=length, fill=wave)) + geom_density(alpha=.8) + theme_bw() + 
  facet_wrap(~outcome, ncol = 1, labeller=labeller(outcome=name)) + xlab('Average answer length (number of words)') + 
  scale_fill_manual(values=c('gray', 'black')) + scale_x_continuous(limits=c(0,300)) + ylab('') +
  theme(panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(), 
        legend.position = 'top', legend.title=element_blank(), axis.text.y = element_blank(), 
        axis.ticks.y = element_blank(), strip.text = element_text(size=10), strip.background = element_rect(fill="white"))

quality_plot

#ggsave(file='Plots/quality_plot.pdf', quality_plot, width = 6, height = 12, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 8
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
quality <- setDT(rbind( data.frame(solution = survey[['Q27']], date=survey[['W2_FinishTime']], wave='Wave two'), 
                        data.frame(solution = survey[['Q20_text']], date=survey[['FinishTime']], wave='Wave one')))
quality[ , length := str_count(quality$solution, ' ')]
quality[, date := as.Date(quality$date, format='%Y-%m-%d')]
quality[, week := format(quality$date, "%W")]
quality <- quality[ , list(mean(length), unique(wave)), by='week']

quality_plot2 <- ggplot(quality, aes(x=as.numeric(week), y=V1, fill=V2)) + geom_histogram(stat='identity', alpha=.7) + theme_bw() + 
  xlab('Week of reply') + ylab('Average answer length\n(number of words)') + 
  scale_fill_manual(values=c('gray', 'black')) + theme(legend.title = element_blank(), legend.position='top')
quality_plot2

#ggsave(file='Plots/quality_plot2.pdf', quality_plot2, width = 7, height = 4, dpi = 1200)


##########################################################
# TABLE 3
##########################################################
names <- c('demand_econ', 'classical_econ', 'health', 'climate_econ', 'protect_econ', 'international_econ',
           'social', 'tax_down', 'helppackages', 'cashtransfer', 'publicspending', 
           'non_avoidable', 'tax_up', 'austerity', 'antipathy', 'interestrate', 'bonds', 'dk_econ')
categories <- list(demand, classical, health, climate, protectionism, international_econ, 
                   social, tax_down, helppackages, cashtransfer, publicspending, 
                   non_avoidable, tax_up, austerity, antipathy, interestrate, bonds, DK)
categories <- lapply(categories, function(x){unique(unlist(str_split(gsub('[a-zæåø ]', '', x, fixed = T), '([[:punct:]]| |\\|)')))})
categories <- lapply(categories, function(x){unique(unlist(text_tokens(x, stemmer='da')))})
size_dictionary <- unlist(lapply(categories, function(x){length(x[str_count(x)>2])}))

matches_w1 <- unlist(sapply(paste(names, '_w1', sep=''), function(x){mean(survey[[x]], na.rm=T)} ))
matches_w2 <- unlist(sapply(names, function(x){mean(survey[[x]], na.rm=T)} ))

size_matches <- setDT(data.frame(name = gsub('_', ' ', names), 
                                 size=size_dictionary, 
                                 matches_wave1 = matches_w1, 
                                 matches_wave2 = matches_w2))
size_matches <- setorderv(size_matches, 'size', order=-1)

table <- stargazer(size_matches, header=F, style='apsr', summary=F, label='tab:dict_descrip', 
                   title='Descriptive data on dictionary categories')
table[7] <- " & Category & \\#words in dictionary & Share of replies (W1) & Share of replies (W2) \\\\ "
table <- gsub('ccccc', 'clccc', table)
#write(table, file='dict_descrip.tex')


##########################################################
# TABLE 4
##########################################################
models <- list()
models[[1]] <- lm(data=size_matches, matches_w1 ~ size)
models[[2]] <- lm(data=size_matches, matches_w2 ~ size)
models[[3]] <- lm(data=size_matches[!(name %in% c('demand econ', 'classical econ', 'health'))], matches_wave1 ~ size)
models[[4]] <- lm(data=size_matches[!(name %in% c('demand econ', 'classical econ', 'health'))], matches_wave2 ~ size)

write(stargazer(models, header=F, style='apsr', summary=F, omit.stat = c('rsq', 'ser', 'adj.rsq', 'f'),
                font.size = 'footnotesize',
                title = 'Correlation between number of dictionary category words and match share in replies',
                label='tab:dicsize', covariate.labels = '\\#words in dictionary', dep.var.labels = c('Matches pct. (w1)', 'Matches pct. (w2)', 'Matches pct. (w1)', 'Matches pct. (w2)'),
                add.lines = list(c('Std.dev., y', round(c(sd(size_matches$matches_wave1, na.rm=T), 
                                                          sd(size_matches$matches_wave2, na.rm=T), 
                                                          sd(size_matches$matches_wave1[!(size_matches$name %in% c('demand econ', 'classical econ', 'health'))], na.rm=T), 
                                                          sd(size_matches$matches_wave2[!(size_matches$name %in% c('demand econ', 'classical econ', 'health'))], na.rm=T)), 3)), 
                                 c('Excl. top-3 categories', 'No', 'No', 'Yes', 'Yes')), 
                notes = 'Top-3 categories include demand econ, classical econ, and health.'),
      file='dicsize.tex')




##########################################################
# TABLE 5
##########################################################

# %%
# WAVE 1
# %%
corpus <- corpus(survey$solution_w1, 
                 docvars = data.frame(party = names(survey$StartTime)))
solutions <- dfm(corpus, 
                 stem = TRUE,
                 remove = stopwords,
                 remove_punct = TRUE,
                 remove_numbers = TRUE)

# %%
# WAVE 2
# %%
corpus <- corpus(survey$solution, 
                 docvars = data.frame(party = names(survey$StartTime)))

solutions_2 <- dfm(corpus, 
                   stem = TRUE,
                   remove = stopwords,
                   remove_punct = TRUE,
                   remove_numbers = TRUE)

# %%
# MANUAL CODING OF FIRST 100 ANSWERS
# %%
# survey$solution[100]
refscores_w2 <- rep(NA, nrow(solutions_2)) # reference categories
refscores_w2[1] <- -1; refscores_w2[3] <- -1; refscores_w2[6] <- 1; refscores_w2[9] <- -1; refscores_w2[10] <- 1; refscores_w2[15] <- 1; refscores_w2[16] <- 1; refscores_w2[17] <- 1; refscores_w2[18] <- -1; refscores_w2[20] <- -1; refscores_w2[24] <- 1; refscores_w2[25] <- 1; refscores_w2[29] <- 1; refscores_w2[30] <- 1; refscores_w2[32] <- -1; refscores_w2[34] <- 1; refscores_w2[39] <- 1; refscores_w2[40] <- 1; refscores_w2[43] <- 1; refscores_w2[46] <- 1; refscores_w2[47] <- 1; refscores_w2[52] <- 1; refscores_w2[58] <- 1; refscores_w2[59] <- -1; refscores_w2[64] <- -1; refscores_w2[66] <- 1; refscores_w2[67] <- 1; refscores_w2[68] <- 1; refscores_w2[70] <- 1; refscores_w2[84] <- -1; refscores_w2[92] <- -1; refscores_w2[93] <- 1; refscores_w2[97] <- 1

# %%
# FITTING MODEL FOR WAVE *1* RESPONSES
# %%
wordscores_model <- textmodel_wordscores(solutions,
                                         refscores_w2,
                                         scale = "linear",
                                         smooth = 1) # Estimating model
wordscores_w1 <- predict(wordscores_model, rescaling = "mv") # Extracting estimates

# %%
# FITTING MODEL FOR WAVE *2* RESPONSES
# %%
wordscores_model <- textmodel_wordscores(solutions_2,
                                         refscores_w2,
                                         scale = "linear",
                                         smooth = 1) # Estimating model
wordscores_w2 <- predict(wordscores_model, rescaling = "mv") # Extracting estimates

survey[, c('wordscore_w1', 'wordscore_w2') := list(wordscores_w1, wordscores_w2)]

# %%
# CORRELATING DICTIONARY MEASURE WITH WORDSCORE
# %%

dist <- quantile(c(wordscores_w1, wordscores_w2), probs=seq(0.01, 0.99, 0.01))

Wordscore1 <- c(wordscores_w1, wordscores_w2); Wordscore <- Wordscore1
models[[1]] <- lm(c(survey$intervention2_w1, survey$intervention2_w2)~
                    Wordscore)
Wordscore2 <- c(wordscores_w1, wordscores_w2)[abs(wordscores_w1)<dist[99] & abs(wordscores_w1)>dist[1]]; Wordscore <- Wordscore2
models[[2]] <- lm(c(survey$intervention2_w1, survey$intervention2_w2)[abs(wordscores_w1)<dist[99] & abs(wordscores_w1)>dist[1]]
                  ~ Wordscore)
Wordscore3 <- c(wordscores_w1, wordscores_w2)[abs(wordscores_w1)<dist[97] & abs(wordscores_w1)>dist[3]]; Wordscore <- Wordscore3
models[[3]] <- lm(c(survey$intervention2_w1, survey$intervention2_w2)[abs(wordscores_w1)<dist[97] & abs(wordscores_w1)>dist[3]]
                  ~ Wordscore)
Wordscore4 <- c(wordscores_w1, wordscores_w2)[abs(wordscores_w1)<dist[90] & abs(wordscores_w1)>dist[10]]; Wordscore <- Wordscore4
models[[4]] <- lm(c(survey$intervention2_w1, survey$intervention2_w2)[abs(wordscores_w1)<dist[90] & abs(wordscores_w1)>dist[10]]
                  ~ Wordscore)

standard_devs <- round(c(sd(Wordscore1, na.rm=T),  sd(Wordscore2, na.rm=T), sd(Wordscore3, na.rm=T), sd(Wordscore4, na.rm=T)), 2)

table <- stargazer(models, style='apsr', header=F, font.size = 'footnotesize', omit.stat = c('rsq', 'ser', 'adj.rsq', 'f'),
                   omit = 'Constant',
                   add.lines = list(c('Std. Dev.', standard_devs)), 
                   notes = '\\parbox[t]{1\\textwidth}{Dictionary measure is a dummy taking the value 1 if a word indicating intervention is identified in the text. Wordscore is a supervised scaling algorithm (\\cite{laver2003extracting}) which scores the individual answer by comparing it to a set of reference texts which we code manually. Specifically, we manually code 100 answers with respect to intervention (1) or non-intervention (0). These texts act as anchor for the algorithm to score the remaining texts on a scale ranging from non-intervention to intervention. The association is estimated for four samples: the full sample and three samples excluding observations with the most extreme values on the wordscore measure. This is to support that the association is not simply driven by clear and obvious (extreme) examples. Interpreting Table \\ref{tab:valid}, we find a positive and statistically significant association between our dictionary and the wordscore measure. In other words, the two measures of economic intervention are in agreement. The association is furthermore practically important. Moving one standard deviation towards intervention on the wordscore measure corresponds to our dictionary measure being 3pct. to 13pct more likely to identify intervention in the same replies.}',
                   dep.var.labels = 'Dictionary measure (Wave 1)', label='tab:valid', title='Validation of dictionary measure: comparison with the wordscore algorithm')
table[8] <- '\\\\[-1.8ex] & \\multicolumn{4}{c}{Dictionary measure}'
table[9] <- "\\\\[1.8ex] & Full sample & Excl. top/bottom 1 pct. & Excl. top/bottom 3 pct. & Excl. top/bottom 10 pct.\\\\"

write(table, file='valid.tex')





# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 9
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

variable <- c('education', 'c_Alder_cat', 'gender', 'ideology')
selection <- NULL
for (i in variable){
  selection <- rbind(selection, data.frame(covariate = survey[[i]], econ_answer = survey[['econ_answer']], wave='Wave two' ))
  selection <- rbind(selection, data.frame(covariate = survey[[i]], econ_answer = survey[['econ_answer_w1']], wave='Wave one' ))}

selection <- setDT(selection)[, list( mean(econ_answer, na.rm=T), sd(econ_answer, na.rm=T), .N), by=c('covariate', 'wave')]
selection <- selection[!is.na(covariate)]
selection[, covariate := gsub('Right', 'Ideological right', gsub('Left', 'Ideological left', gsub('år', 'years', covariate)))]
Encoding(selection$covariate) <- 'UTF-8'

selection[, covariate := factor(covariate, levels=c('Female', 'Male', '18-34 years', '35-49 years', '50-64 years', '65+ years',
                                                    'Elementary', 'Vocational', 'High school', 'Higher (short)', 'Higher (medium)', 
                                                    'Higher (long)', 'Doctorate', 'Ideological right', 'Ideological left'))]

selection_plot <- ggplot(selection, aes(x=covariate, y=V1, col=wave, ymin=V1-1.96*(V2/sqrt(N)), ymax=V1+1.96*(V2/sqrt(N)))) + 
  geom_errorbar(width=0, lwd=1.3, alpha=.4) + theme_bw() + xlab('') + ylab('Economic reply (probability)') + 
  geom_point(size=4, col='white', alpha=1) + geom_point(size=4, alpha=.4) + coord_flip() + 
  scale_color_manual(values=c('black', 'gray')) + theme(legend.text = element_text(size=15), legend.title = element_blank())
selection_plot

# ggsave(file='Plots/selection_plot.pdf', selection_plot, width = 7, height = 5, dpi = 1200)


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FIGURE 10
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
variables_diff2 <- c('within_demand', 'within_classical')
variable <- c('education', 'c_Alder_cat', 'gender', 'ideology')
design1 <- NULL
for (i in 1:length(variable)){
  for (g in 1:length(variables_diff2)){
    survey[, loop_var :=  NULL ]
    survey[, loop_var := as.numeric(survey[[variables_diff2[g]]]) ]
    loop_dta <- survey[, list(mean(loop_var, na.rm=T), .N, sd(loop_var)), 
                     by=c(variable[i])][, c('sderror', 'outcome', 'independent') := list(V3 / sqrt(N), variables_diff2[g], variable[i])]
    names(loop_dta)[1] <- 'categories'
    design1 <- rbind(design1, loop_dta)}}

name1 <- c('Intervention', 'Non-intervention')
names(name1) <- variables_diff2
name2 <- c('Education', 'Age', 'Gender', 'Ideology')
names(name2) <- variable

design1[, categories := factor(categories, 
                               levels=c('Elementary', 'Vocational', 'High school', 'Higher (short)', 'Higher (medium)', 'Higher (long)', 
                                        '18-34 år', '35-49 år', '50-64 år', '65+ år', 'Female', 'Male', 'Left', 'Right')) ]
design1 <- design1[!is.na(categories)]
design1[, categories := gsub('år', 'years', categories)]

covariates <- ggplot(data=design1, aes(x=categories, y=V1, ymin=V1-1.96*sderror, ymax=V1+1.96*sderror)) + 
  facet_grid(outcome~independent, scales = 'free', switch='y', labeller=labeller(outcome=name1, independent=name2)) + xlab('') + geom_point() +
  theme_bw() + scale_y_continuous(limits=c(-.3, .3)) + ylab('Within-respondent difference\n between wave one and wave two') + geom_hline(yintercept=0, lty=2) +
  geom_errorbar(width=.2, lwd=1) + 
  theme(axis.text.x = element_text(angle = 45, hjust=1), legend.position = 'top', legend.title = element_blank(), strip.text = element_text(size=15), strip.background =element_rect(fill="white"),
        panel.grid.major.x = element_blank(), axis.text=element_text(size=13), axis.title=element_text(size=15), panel.grid.minor.x = element_blank()) + 
  scale_fill_manual(values=c('black', 'gray40'))
covariates

#ggsave(file='Plots/covariates.pdf', covariates, width = 8, height = 5.5, dpi = 1200)



# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# IDEOLOGICAL LEANING WITH CONTROLS
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

w1_0 <- felm(intervention2_w1 ~ coalition | 0 | 0 | 0, data=survey)
w2_0 <- felm(intervention2_w2 ~ coalition | 0 | 0 | 0, data=survey)
w1_1 <- felm(intervention2_w1 ~ coalition + Alder + c_Koen + unemployment + q1 | c_Kommunekode | 0 | 0, data=survey)
w2_1 <- felm(intervention2_w2 ~ coalition + Alder + c_Koen + unemployment + q1 | c_Kommunekode | 0 | 0, data=survey)
w1_2 <- felm(intervention2_w1 ~ coalition + Alder + c_Koen + unemployment + q1 | c_Postnummer | 0 | 0, data=survey)
w2_2 <- felm(intervention2_w2 ~ coalition + Alder + c_Koen + unemployment + q1 | c_Postnummer | 0 | 0, data=survey)


table <- stargazer(list(w1_0, w2_0, w1_1, w2_1, w1_2, w2_2), header=F, title='Reduction in ideological polarization before and after the dip in the economy', 
                   covariate.labels = c('Ideological right', 'Age', 'Male', 'Unemployed', 'Education'), 
                   add.lines = list(c('Fixed effects', '-', '-', 'municipality', 'municipality', 'zip code', 'zip code')), 
                   digits = 2, notes.append=T, omit.stat = c('rsq', 'ser', 'adj.rsq'), style='apsr',
                   label='reg_coalition',
                   dep.var.labels = c('Wave 1', 'Wave 2', 'Wave 1', 'Wave 2', 'Wave 1', 'Wave 2'), font.size = 'footnotesize',
                   notes = '\\parbox[t]{.9\\textwidth}{Note Ideological right includes Danish Folkparty, Liberals, The Conservative Folkparty, The New Right, and Liberal Alliance. Ideological left is the remaining parties from Figure \\ref{fig:partisan}.
          Unemployed takes the form of a dummy. Education is a numeric variable indicating the highest education obtained (0 = primary school, 8 = PhD)}')
table <- c(table[1:7], '& \\multicolumn{6}{c}{Support for economic intervention to combat the Covid19 pandemic}\\\\ ', table[8:22], "\\hline \\hline \\\\[-1.8ex] ", table[23:30])

write(table,file='reg_coalition.tex')

# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# PARTY WITH CONTROLS
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

survey[, party2 := relevel(as.factor(party), ref = 10)]
models <- list()
models[[1]] <- felm(intervention2_w1 ~ as.factor(party2) | 0 | 0 | 0, data=survey)
models[[2]] <- felm(intervention2_w2 ~ as.factor(party2) | 0 | 0 | 0, data=survey)
models[[3]] <- felm(intervention2_w1 ~ as.factor(party2) + Alder + c_Koen + unemployment + q1 | c_Kommunekode | 0 | 0, data=survey)
models[[4]] <- felm(intervention2_w2 ~ as.factor(party2) + Alder + c_Koen + unemployment + q1 | c_Kommunekode | 0 | 0, data=survey)
models[[5]] <- felm(intervention2_w1 ~ as.factor(party2) + Alder + c_Koen + unemployment + q1 | c_Postnummer | 0 | 0, data=survey)
models[[6]] <- felm(intervention2_w2 ~ as.factor(party2) + Alder + c_Koen + unemployment + q1 | c_Postnummer | 0 | 0, data=survey)

model_dta <- lapply(models, function(x){setDT(data.frame(rownames(summary(x)$coef[grepl('as.factor', rownames(summary(x)$coef)) , 1:2]), 
                                                         summary(x)$coef[grepl('as.factor', rownames(summary(x)$coef)) , 1:2]))})
wave <- rep(c('Wave 1', 'Wave 2'), 3)
spec <- c('Bivariate', 'Bivariate', 'Municipality fe', 'Municipality fe', 'Zip code fe', 'Zip code fe')

for (i in 1:length(model_dta)){
  model_dta[[i]]$spec <- spec[i]
  model_dta[[i]]$wave <- wave[i]}

model_dta <- rbindlist(model_dta)
model_dta[, party := gsub('as.factor(party2)', '', model_dta[[1]], fixed=T)]
model_dta <- setDT(rbind(model_dta, data.frame(t(c('The Socialdemocrats', 0, 0, 'Bivariate', 'Wave 1', 'The Socialdemocrats'))), use.names=FALSE))

model_dta[, c('Estimate', 'Std..Error') := list(as.numeric(Estimate), as.numeric(`Std..Error`))]
model_dta[, c('lower', 'upper') := list(Estimate - `Std..Error`*1.96, 
                                        Estimate + `Std..Error`*1.96)]

model_dta[, party := list(factor(party, levels=c('Enhedslisten', 'Alternativet', 'Socialistisk Folkeparti', 
                                                 'The Socialdemocrats', 'Radikale Venstre', 'Dansk Folkeparti', 
                                                 'Venstre', 'Det Konservative Folkeparty', 'Nye Borgerlige', 
                                                 'Liberal Alliance')))]
model_dta <- model_dta[!is.na(party)]
setorderv(model_dta, c('party', 'spec', 'wave'))

party_reg <- ggplot(data = model_dta, aes(x = party, y = Estimate, ymin=lower, ymax=upper, col=wave, pch=spec)) + 
  geom_hline(yintercept=0, lty=2) + theme_bw() + scale_color_manual(values=c('black', 'gray60')) + 
  geom_errorbar(width=.4, lwd=1.2, position=position_dodge(.8)) + geom_point(size=2, position=position_dodge(.8)) + 
  coord_flip() + ylab('Support for intervention') + xlab('') + 
  scale_x_discrete(labels=english) +
  theme(legend.title = element_blank(), axis.text = element_text(size=15), 
        axis.title= element_text(size=15), legend.text = element_text(size=15))
party_reg

#ggsave(file='Plots/party_reg_controls.pdf', party_reg, width = 12, height = 5, dpi = 1200)








